import axios from 'axios';
import { resetRouter } from '@/router';
import { getToken, removeAll } from '@/utils/cache';
import { Message } from 'element-ui';

const _methods = ['post', 'put', 'patch'];
const _delQuery = ['', null, undefined];

axios.defaults.withCredentials = true;
const service = axios.create({
  timeout: 20000
});

service.interceptors.request.use(config => {
  config.headers['access_token'] = getToken() || '';
  if (_methods.includes(config.method)) {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    const data = config.data;
    if (data) {
      for (const k in data) {
        if (_delQuery.includes(data[k])) Reflect.deleteProperty(config.data, k);
      }
    }
  } else {
    const params = config.params;
    for (const k in params) {
      if (params[k] === '') Reflect.deleteProperty(config.params, k);
    }
  }
  return config;
}, error => {
  Promise.reject(error);
});

// 错误状态码
const responseCode = ['AUTH.SERVER.E0001', 'AUTH.RESOURCE.E0001', 'AUTH.SERVER.E0002', 'AUTH.RESOURCE.E0002'];

service.interceptors.response.use(
  response => {
    const { success, errorCode, exceptionContent } = response.data;
    if (success === false) {
      Message.closeAll();
      if (responseCode.includes(errorCode)) {
        Message({ message: exceptionContent || '登录信息过期，请重新登录', type: 'error', showClose: true });
        setTimeout(() => {
          removeAll();
          const yhzxUrl = sessionStorage.getItem('yhzx_url');
          if (yhzxUrl) {
            window.location.href = yhzxUrl;
          } else {
            resetRouter();
          }
        }, 1000);
      } else {
        Message({ message: exceptionContent || '操作失败，请重试！', type: 'error', showClose: true });
      }
    }
    return response.data;
    // return response.config.responseType ? { // 如果是blob类型，需要特殊处理下
    //   ...response.headers,
    //   file: response.data
    // } : response.data;
  }, error => {
    Message.closeAll();
    Message({ message: '连接失败！', type: 'error' });
    return Promise.reject(error);
  }
);

export default service;
